package net.adetech.cjg.outerservice.web;


import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import net.adetech.cjg.outerservice.utils.BankUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.WriteAbortedException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class WebController {

    @Autowired
    BankUtil bankUtil;

    @RequestMapping("/qrcode")
    public ResponseEntity<byte[]> getQrcode(String seqno,String amount,String title) throws IOException,WriterException
    {
        int width  = 150;
        int height = 150;
        String format = "png";
        JSONObject urlJson = bankUtil.getQrcode(seqno, "bu"+seqno,title,amount);
        String url = urlJson.getString("code_url");
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
        //将矩阵转为Image
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, format, out);//将BufferedImage转成out输出流
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.CREATED);
    }

}
